package com.earthquake.monitor_system.service.impl;

import com.earthquake.monitor_system.service.ITF.IUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadImp implements IUpload {
    @Value("${file.uploadPath}")
    private String uploadPath;
    @Value("${file.serveRootPath}")
    private String serveRootPath;
    public String uploadImg(MultipartFile multipartFile,String dir) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String imgSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + imgSuffix;
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY/MM/DD");
        String dataPath = dateFormat.format(new Date());
        File targetFilePath = new File(uploadPath+dir,dataPath);
        if(!targetFilePath.exists()) {
            targetFilePath.mkdirs();
        }
        File targetFileName = new File(targetFilePath,newFileName);
        multipartFile.transferTo(targetFileName);
        String fileName=  dir+"/"+dataPath+"/"+newFileName;
        return serveRootPath+fileName;
    }

}
